package cn.wowjoy.office.materialmanage.addReport;

import android.arch.lifecycle.Observer;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;

import cn.wowjoy.office.R;
import cn.wowjoy.office.baselivedata.appbase.LiveDataWrapper;
import cn.wowjoy.office.baselivedata.appbase.NewBaseActivity;
import cn.wowjoy.office.common.adapter.StockRecordAdapter;
import cn.wowjoy.office.common.decoration.SimpleItemDecoration;
import cn.wowjoy.office.common.widget.CommonDialog;
import cn.wowjoy.office.common.widget.CreateDialog;
import cn.wowjoy.office.common.widget.MDialog;
import cn.wowjoy.office.data.remote.ResultEmpty;
import cn.wowjoy.office.data.response.RecordResponse;
import cn.wowjoy.office.data.response.StockRecordResponse;
import cn.wowjoy.office.databinding.ActivityStockRecordeBinding;
import cn.wowjoy.office.materialmanage.inventory.MaterialInventoryActivity;

@Route(path = "/materialmanage/addReport/stockRecord")
public class StockRecordeActivity extends NewBaseActivity<ActivityStockRecordeBinding,AddStockViewModel> implements View.OnClickListener {

    @Autowired
    String goodsCode;
    @Autowired
    String barCode;
    @Autowired
    String headCode;
    @Autowired
    boolean isCanNotEdit;
    @Autowired
    boolean isNotInReport;

    private boolean isManualAdd;
    private CommonDialog deleteDialog;

    private MDialog waitDialog;

    private void clearDialog(){
        if (waitDialog != null ){
            waitDialog.dismiss();
            waitDialog = null;
        }
    }


    private void showDeleteDialog(){
        if (null == deleteDialog)
            deleteDialog = new CommonDialog.Builder()
                    .setTitle("提示")
                    .setContentGravity(Gravity.CENTER)
                    .setContent("是否需要删除该手工录入的信息？")
                    .setContentColor(R.color.appText)
                    .setCancelBtn("否", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            deleteDialog.dismissAllowingStateLoss();
                        }
                    })
                    .setConfirmBtn("是", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            viewModel.adapter.deleteRecord(selectedRecordResponse);
                            selectedRecordResponse = null;
                            deleteDialog.dismissAllowingStateLoss();
                            //删除adapter的item
                        }
                    })
                    .create();
        deleteDialog.show(getSupportFragmentManager(),null);
    }


    @Override
    protected Class<AddStockViewModel> getViewModel() {
        return AddStockViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_stock_recorde;
    }

    @Override
    protected ViewGroup getErrorViewRoot() {
        return binding.errorContent;
    }

    @Override
    protected void refreshError() {
        super.refreshError();
        if (isNotInReport){
            viewModel.getDetail();
        } else {
            viewModel.getRecord();
        }

    }

    private int notifyPosition;
    private int editIemPosition;
    private RecordResponse selectedRecordResponse;

    @Override
    protected void init(Bundle savedInstanceState) {
        ARouter.getInstance().inject(this);
        binding.setViewmodel(viewModel);
        viewModel.setBarCode(barCode);
        viewModel.setHeadCode(headCode);
        viewModel.setGoodsCode(goodsCode);
        initView();
        initObserver();
        if (isNotInReport){
            viewModel.getDetail();
        } else {
            viewModel.getRecord();
        }

    }
    private void initView(){
        viewModel.adapter.setCanNotEdit(isCanNotEdit);
        if (isCanNotEdit){
            binding.toolbarTitle.setText("查看详情");
            binding.save.setVisibility(View.GONE);
            binding.fab.setVisibility(View.GONE);
        } else {
            binding.toolbarTitle.setText("库存录入");
            binding.save.setVisibility(View.VISIBLE);
            binding.fab.setVisibility(View.VISIBLE);
        }
        binding.back.setOnClickListener(this);
        binding.save.setOnClickListener(this);
        binding.fab.setOnClickListener(this);
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        binding.recyclerView.setAdapter(viewModel.adapter);
        binding.recyclerView.addItemDecoration(new SimpleItemDecoration(this,SimpleItemDecoration.VERTICAL_LIST));
        binding.recyclerView.setNestedScrollingEnabled(false);
    }
    private void initObserver(){
        viewModel.result.observe(this, new Observer<LiveDataWrapper<StockRecordResponse>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<StockRecordResponse> stockRecordResponseLiveDataWrapper) {
                switch (stockRecordResponseLiveDataWrapper.status){
                    case LOADING:
                        clearDialog();
                        waitDialog = CreateDialog.waitingDialog(StockRecordeActivity.this);
                        break;
                    case SUCCESS:
                        clearDialog();
                        setModel(stockRecordResponseLiveDataWrapper.data);
                        break;
                    case ERROR:
                        clearDialog();
                        handleException(stockRecordResponseLiveDataWrapper.error,true);
                        break;
                }
            }
        });

        viewModel.edit.observe(this, new Observer<RecordResponse>() {
            @Override
            public void onChanged(@Nullable RecordResponse recordResponse) {
                notifyPosition = recordResponse.getNotifyPosition();
                ARouter.getInstance().build("/materialmanage/addReport/addStock")
                        .withString("stock",recordResponse.getRealStockCount())
                        .navigation(StockRecordeActivity.this,200);
            }
        });

        viewModel.jumpTo.observe(this, new Observer<RecordResponse>() {
            @Override
            public void onChanged(@Nullable RecordResponse recordResponse) {
                editIemPosition = recordResponse.getEditIemPosition();
                editStock(false,recordResponse);
            }
        });

        viewModel.save.observe(this, new Observer<LiveDataWrapper<ResultEmpty>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<ResultEmpty> resultEmptyLiveDataWrapper) {
                switch (resultEmptyLiveDataWrapper.status){
                    case LOADING:
                        clearDialog();
                        waitDialog = CreateDialog.waitingDialog(StockRecordeActivity.this);
                        break;
                    case SUCCESS:
                        clearDialog();
                        Intent intent = new Intent();
                        intent.putExtra("isSave",true);
                        setResult(RESULT_OK,intent);
                        finish();
                        break;
                    case ERROR:
                        clearDialog();
                        handleException(resultEmptyLiveDataWrapper.error,false);
                        break;
                }
            }
        });
        viewModel.delete.observe(this, new Observer<RecordResponse>() {
            @Override
            public void onChanged(@Nullable RecordResponse recordResponse) {
                selectedRecordResponse = recordResponse;
                showDeleteDialog();
            }
        });

    }

    private void setModel(StockRecordResponse response){
        binding.setModel(response);
        viewModel.adapter.setDatas(response.getRecordResponses());
        if (Double.parseDouble(response.getCount()) == 0){
            binding.count.setTextColor(getResources().getColor(R.color.appText10));
            binding.money.setTextColor(getResources().getColor(R.color.appText10));
        } else if (Double.parseDouble(response.getCount()) < 0){
            binding.count.setTextColor(getResources().getColor(R.color.menu_look_error));
            binding.money.setTextColor(getResources().getColor(R.color.menu_look_error));
        } else {
            binding.count.setTextColor(getResources().getColor(R.color.decorateGreenHighLight));
            binding.money.setTextColor(getResources().getColor(R.color.decorateGreenHighLight));
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case 200:
                if (null != data){
                    String count = data.getStringExtra("count");
                    viewModel.adapter.notifyRealStock(notifyPosition,count);
                }
                break;
            case 300:
                if (null != data){
                    RecordResponse recordResponse = (RecordResponse) data.getSerializableExtra("record");
                    if (isManualAdd){
                        viewModel.adapter.addRecord(recordResponse);
                    } else {
                        viewModel.adapter.changeItem(editIemPosition,recordResponse);
                    }

                }
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.back:
                onBackPressed();
                break;
            case R.id.save:
                //保存录入
                viewModel.save();
                break;
            case  R.id.fab:
                //添加记录
                editStock(true,null);
//                ARouter.getInstance().build("/materialmanage/addreport/editstock")
//                        .navigation(StockRecordeActivity.this,300);
                break;
        }
    }


    private void editStock(boolean isManualAdd,RecordResponse record){
        this.isManualAdd = isManualAdd;
        ARouter.getInstance().build("/materialmanage/addreport/editstock")
                .withBoolean("isManualAdd",isManualAdd)
                .withSerializable("record",record)
                .withString("headCode",headCode)
                .withString("goodsCode",goodsCode)
                .navigation(StockRecordeActivity.this,300);
    }

}
